$(function() {
	/*
	 * 初始化 select
	 */
	$('select').select2();

	/*
	 * 初始化编辑器
	 */
	var newsEditor = CKEDITOR
			.replace(
					'news-editor',
					{
						language : 'zh-cn',
						toolbar : 'Basic',
						height : 480,
						uiColor : '#FFFFFF',
						extraPlugins : 'uploadimage',
						uploadUrl : '/base/upload/uploadFile',
						filebrowserUploadUrl : '/base/upload/uploadFile',
						toolbarGroups : [
								{
									name : 'document',
									groups : [ 'mode', 'document', 'doctools' ]
								},
								{
									name : 'clipboard',
									groups : [ 'clipboard', 'undo' ]
								},
								{
									name : 'editing',
									groups : [ 'find', 'selection',
											'spellchecker', 'editing' ]
								},
								{
									name : 'forms',
									groups : [ 'forms' ]
								},
								{
									name : 'basicstyles',
									groups : [ 'basicstyles', 'cleanup' ]
								},
								{
									name : 'insert',
									groups : [ 'insert' ]
								},
								{
									name : 'paragraph',
									groups : [ 'list', 'indent', 'blocks',
											'align', 'bidi', 'paragraph' ]
								}, {
									name : 'links',
									groups : [ 'links' ]
								}, {
									name : 'styles',
									groups : [ 'styles' ]
								}, {
									name : 'colors',
									groups : [ 'colors' ]
								}, {
									name : 'tools',
									groups : [ 'tools' ]
								}, {
									name : 'others',
									groups : [ 'others' ]
								}, {
									name : 'about',
									groups : [ 'about' ]
								} ],
						removeButtons : 'Save,Templates,Copy,Cut,Paste,Undo,Redo,Replace,Find,Scayt,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Superscript,Subscript,Strike,Underline,Italic,NumberedList,BulletedList,Outdent,Indent,Blockquote,CreateDiv,JustifyLeft,JustifyCenter,JustifyRight,JustifyBlock,Language,BidiRtl,BidiLtr,Unlink,Link,Anchor,Flash,Table,HorizontalRule,Smiley,SpecialChar,PageBreak,Iframe,Styles,Format,Font,FontSize,TextColor,BGColor,Maximize,ShowBlocks,About,NewPage,Preview,Print'
					});

	newsEditor
			.on(
					'fileUploadRequest',
					function(evt) {
						var fileLoader = evt.data.fileLoader, formData = new FormData(), xhr = fileLoader.xhr;
						xhr.open('POST', fileLoader.uploadUrl, true);
						formData.append('file', fileLoader.file,
								fileLoader.fileName);
						fileLoader.xhr.send(formData);
						evt.stop();
					}, null, null, 6);

	newsEditor.on('fileUploadResponse', function(evt) {
		console.log(evt.data);
		var resData = JSON.parse(evt.data.fileLoader.xhr.response);
		evt.stop();
		// Ger XHR and response.
		var data = evt.data;
		if (resData.errorCode == 1) {
			// Error occurred during upload.
			data.message = resData.msg;
			evt.cancel();
		} else {
			data.message = resData.msg;
			data.url = resData.data.replace(/([^.]*).([^.]*)$/g, '$1_l.$2');
		}
	});

	newsEditor.on('change', function(evt) {
		console.log(newsEditor.getData().length);
	});

	/*
	 * 初始化消息弹窗
	 */
	$('#msg-modal,#pic-modal').modal({
		backdrop : 'static',
		keyboard : false,
		show : false
	});

	/*
	 * 表单验证错误 显示/隐藏
	 */
	function toggleError(show, ele, msg) {
		if (ele.next().length == 0) {
			ele
					.after('<label class="err-label"><i class="fa fa-times-circle-o"></i><span></span></label>');
		}
		if (show) {
			ele.next().show().find('span').html(msg);
			ele.parent().addClass('has-error');
		} else {
			ele.parent().removeClass('has-error');
			ele.next().hide();
		}
	}

	/*
	 * 初始化图片上传按钮
	 */
	var $coverUploading = $('#cover-upload-box .overlay').hide();

	var uploader = new PicUploader({
		success : function(obj) {
			var picUrl = obj['data'];
			$coverUploading.hide();
			$('[name="coverPic"]').val(picUrl);
			$('.thumbnail').css('background-image', 'url(' + picUrl + ')');
		}
	});
	$('.thumbnail').on('click', function() {
		uploader.start();
		$coverUploading.click();
	});
	$('#cover-pic').on(
			'change',
			function() {
				var picFormData = new FormData();
				picFormData.append('file', this.files[0]);
				$coverUploading.show();
				$.ajax({
					url : '/base/upload/uploadFile',
					type : 'post',
					data : picFormData,
					dataType : 'json',
					cache : false,
					contentType : false,
					processData : false,
					success : function(obj) {
						if (obj.errorCode == 0) {
							$coverUploading.hide();
							$('.thumbnail').css('background-image',
									'url(' + obj.data + ')');
							$('#coverPicUrlInput').val(obj.data);
						} else {
						}
					}
				});
			});

	/*
	 * 保存资讯
	 */
	function save() {

		if ($.trim(newsEditor.getData()).length == 0 || $.trim(newsEditor.getData()).length >= 120000) {
			greeting({
				title : '提示',
				msg : '资讯正文必须在1-100000字之内'
			});
			return false;
		}

		if ($.trim($('#coverPicUrlInput').val()).length == 0) {
			greeting({
				title : '提示',
				msg : '请上传主题图'
			});
			return false;
		}

		/* 推荐人数据 */
		var referrerObj = null;
		$('#referee .guest-thumb').each(function() {
			var $this = $(this);
			var referrerDataObj = {};
			$('input', $this).each(function() {
				var $this = $(this);
				referrerDataObj[$this.attr('name')] = $this.val();
			});
			referrerObj = referrerDataObj;
		});

		/* 相关人物数据数组 */
		var relatedmanObjArr = [];
		$('#relatedmen .guest-thumb').each(function() {
			var $this = $(this);
			var relatedmanDataObj = {};
			$('input', $this).each(function() {
				var $this = $(this);
				relatedmanDataObj[$this.attr('name')] = $this.val();
			});
			relatedmanObjArr.push(relatedmanDataObj);
		});

		/* 推荐热文 */
		var hotNewsString = "";
		var len = $('#hot-news-list li').length;
		$('#hot-news-list li').each(function(m) {
			hotNewsString += $(this).data('news-id');
			if (m != (len - 1)) {
				hotNewsString += ",";
			}
		});

		var formData = {};
		var url = $('input[name="newsId"]').length > 0 ? '/cms/news/edit'
				: '/cms/news/add';
		$('#news-editor').val(newsEditor.getData());
		$('#news-form :input').each(function() {
			formData[$(this).attr('name')] = $(this).val();
		});
		formData['referee'] = JSON.stringify(referrerObj);
		formData['relatedPersonnel'] = JSON.stringify(relatedmanObjArr);
		formData['hotNews'] = hotNewsString;

		cAjax({
			url : url,
			data : formData,
			dataType : 'json',
			cache : false,
			success : function(obj) {
//				$('#msg-modal').modal('show');
				location.href = '/cms/news/list';
			}
		});
	}

	/*
	 * 初始化表单验证
	 */
	$('#news-form').validate({
		rules : {
			title : {
				required : true,
				maxlength : 30
			},
			authorName : {
				required : true,
				maxlength : 10
			},
			editName : "required",
			resourceFrom : {
				required : true,
				maxlength : 20
			},
			recommendText : {
				required : true,
				maxlength : 500
			},
//			content : {
//				required : false,
//				maxlength : 10000
//			}
		},
		messages : {
			"title" : {
				maxlength: "标题必须在30字之内"	

			},
			"authorName" : {
				maxlength : "作者必须在10字之内",
			},
			"resourceFrom" : {
				maxlength : "来源必须在20字之内",
			},
			"recommendText" : {
				maxlength : "推荐语/导语必须在500字之内",
			},
//			"content" : {
//				maxlength : "<font style='color:red'>资讯正文必须在10000字之内</font>",
//			}
		},
		ignore : ".input-keyword",
		showErrors : function(errorMap, errorList) {
			if (errorList.length == 0) {
				return;
			} else {
				var msg = '', curEle;
				if (errorList.length > 0) {
					var err = errorList[0], curEle = $(err.element);
					if (err.method == 'required') {
						msg = curEle.prev().html() + "不能为空";
					} else {
						msg = err.message;
					}
				}
				toggleError(true, curEle, msg);
			}
		},
		submitHandler : function() {
			save();
		},
		onkeyup : function(ele) {
			toggleError(false, $(ele));
		}
	});

	$('#news-save-btn').on('click', function() {
		if ($('input[name="id"]').length == 0) {
			$('#isPublished').val(0);
		}
		$('#news-form').submit();
	});

	/*
	 * 增加嘉宾
	 */
	var $guestModal = $('#guest-modal');
	$guestModal.modal({
		backdrop : 'static',
		keyboard : false,
		show : false
	});
	$('#' + $('#user-type-radio :radio:checked').attr('data-target')).show();
	$('#user-type-radio :radio').on('change', function() {
		var $this = $(this);
		var $panelToShow = $('#' + $this.attr('data-target'));
		$('.guest-panel:visible').slideUp();
		$panelToShow.slideDown();
	});
	var personType = '';
	var $curGuestContainer = null;
	$guestModal.on('show.bs.modal', function() {
		$guestModal.find('.person-type').html(personType);
	});
	$('#add-guest-btn').on('click', function() {
		personType = '推荐人';
		$curGuestContainer = $('#referee');
		var MAX = 1;
		if ($('#referee').find('.guest-thumb').length >= MAX) {
			greeting({
				title : '提示',
				msg : '推荐人只能添加一个'
			});
			return;
		}
		$guestModal.modal('show');
	});

	$('#add-relatedman-btn').on('click', function() {
		personType = '相关人物';
		$curGuestContainer = $('#relatedmen');
		$guestModal.modal('show');
	});

	var $addGuestForm = $('#add-guest-form');
	var $guestContainer = $('.guest-container');
	$guestContainer.on('click', '.btn-remove', function() {
		var $this = $(this);
		actionConfirm({
			msg : '确定删除这个' + $this.parents('.box').find('.box-title').html()
					+ '吗？',
			confirm : function() {
				$this.fadeOut({
					complete : function() {
						$this.remove();
					}
				});
			}
		});
	});

	$('.form-group label', $addGuestForm).append('<span></span>');
	$guestContainer.popover({
		selector : '.btn-remove',
		trigger : 'hover',
		html : true,
		content : function() {
			var $this = $(this);
			var html = '<div>' + '<p>姓名:' + $this.find('[name="name"]').val()
					+ '</p>' + '<p>公司:' + $this.find('[name="company"]').val()
					+ '</p>' + '<p>职务:' + $this.find('[name="position"]').val()
					+ '</p>' + '</div>';
			return html;
		}
	});
	$addGuestForm.validate({
		debug : true,
		errorClass : 'has-error',
		ignore : '.ignore',
		submitHandler : function() {
			var inputDataObj = {};
			var tpl = $('#guest-tpl').html();
			$(':input', $addGuestForm).each(function() {
				var $this = $(this);
				inputDataObj[$this.attr('name')] = $this.val();
			});
			var $guestEle = swig.render(tpl, {
				locals : inputDataObj
			});
			$curGuestContainer.find("template").before($guestEle);
			$guestModal.modal('hide');
			$(':input', $addGuestForm).val('');
			$guestAvatarUploadBtn.css('background-image', '');
		},
		showErrors : function(errorMap, errorList) {
			for ( var index in errorList) {
				var error = errorList[index];
				var $ele = $(error.element);
				if ($ele.attr('name') == 'head_url') {
					$guestAvatarUploadBtn.tooltip('show');
				} else {
					$ele.parent().addClass('has-error');
					$ele.siblings('label').find('span').html(
							' (' + error.message + ')').show();
				}
			}
		}
	});

	$('#nonapp-guest .confirm-btn').on('click', function() {
		var $errEle = $('.has-error', $addGuestForm);
		$errEle.removeClass('has-error').find('label span').hide();
		$addGuestForm.submit();
	});

	/* 上传头像 */
	var $guestAvatarUploadBtn = $('#guest-avatar-upload');
	$guestAvatarUploadBtn.tooltip({
		title : '必须上传头像',
		placement : 'auto',
		trigger : 'manual',
		container : '#guest-avatar-upload'
	});
	var guestAvatarUploader = new PicUploader({
		success : function(obj) {
			$guestAvatarUploadBtn.css('background-image', 'url(' + obj['data']
					+ ')');
			$guestAvatarUploadBtn.siblings('input').val(obj['data']);
			$guestAvatarUploadBtn.tooltip('hide');
		}
	});
	$guestAvatarUploadBtn.on('click', function() {
		guestAvatarUploader.start();
	});

	/*
	 * 添加app用户
	 */
	$('.suggest', $guestModal).on('click', 'a', function() {
		var $this = $(this);
		var tpl = $('#guest-tpl').html();
		var $guestEle = swig.render(tpl, {
			locals : $this.data('userData')
		});
		$curGuestContainer.prepend($guestEle);
		$guestModal.modal('hide');
	});

	$('.app-user-search', $guestModal).on('change', function() {
		var $this = $(this);
		var seachWords = $this.val();
		var suggestTplStr = $('#app-guest .tpl').html();
		var $suggestContainer = $('#app-guest .suggest');
		cAjax({
			url : '/base/api/searchUserByName',
			type : 'get',
			data : {
				keywords : seachWords
			},
			success : function(obj) {
				var items = obj['data'];
				$suggestContainer.empty();
				for ( var index in items) {
					var data = items[index];
					var $itemEle = $(swig.render(suggestTplStr, {
						locals : {
							item : data
						}
					}));
					$itemEle.data('userData', data);
					$suggestContainer.append($itemEle);
				}
			}
		});
	});

	/*
	 * 渲染推荐人
	 */
	var refereeObject = $("#referee").data("referee");
//	if (refereeObject != '') {
//		var tpl = $('#referee-tpl').html();
//		var $guestEle = swig.render(tpl, {
//			locals : refereeObject
//		});
//		$('#referee').prepend($guestEle);
//	}

	// 渲染相关人物
	var refereeObject = $("#relatedmen").data("relatedmen");
	var lengthR = refereeObject.length;
	var i;
	for (i = 0; i < lengthR; i++) {
		var tpl = $('#relatedmen-tpl').html();
		var $guestEle = swig.render(tpl, {
			locals : refereeObject[i]
		});
		$('#relatedmen').find("template").before($guestEle);
	}

	// 渲染热文
	// var hotNewsObject = $(".hot-news-box").data("hot-news");
	// var lengthH = hotNewsObject.length;
	// var j;
	// for (j = 0; j < lengthH; j++) {
	// var tpl = $('#hot-news-tpl').html();
	// var $hotNews = swig.render(tpl, {
	// locals : hotNewsObject[j]
	// });
	// $('#hot-news-list').prepend($hotNews);
	// }

	// 搜索
	var serarchNews = function(e) {
		var seachWords = $(e).val();
		if (seachWords != '' && seachWords != "undefined") {
			cAjax({
				url : '/cms/news/getByKeyword',
				type : 'get',
				data : {
					keyword : seachWords
				},
				success : function(obj) {
					var items = obj['data'];
					items = jQuery.parseJSON(items);
					$("#hot-news-result").empty();
					var str = '';
					for ( var index in items) {
						var data = items[index];
						str += '<li class="list-group-item" data-news-id="'
								+ data.newsId + '" data-title="' + data.title
								+ '" data-author-name="' + data.authorName
								+ '">' + data.newsId + '  《' + data.title + '》'
								+ '【' + data.authorName + '】</li>';
					}
					$("#hot-news-result").html(str);
				}
			});
		}
	}

	// 检索资讯
	$(".input-keyword").change(function() {
		serarchNews(this);
	}).keyup(
			function(e) {
				var ev = e || window.event;
				if (ev.keyCode == 13 || ev.keyCode == 8 || ev.keyCode == 40
						|| ev.keyCode == 32) {
					serarchNews(this);
				}
			})

	// 选择资讯
	$("#hot-news-result")
			.on(
					"click",
					'li',
					function() {
						var str = $(this)
								.append(
										'<a href="javascript:;" class="btn btn-xs btn-danger btn-del-hot"><i class="fa fa-remove"></i></a>');
						$("#hot-news-list").append(str);
						$("#hot-news-result").empty();
					})

	$("#hot-news-list").on("click", '.btn-del-hot', function() {
		$(this).parent().remove();
	})
	
	
});
